package com.liruo.enumconverter.core.mybatis;

import com.liruo.enumconverter.core.converter.SourceEnumGenericConverter;
import com.liruo.enumconverter.model.SourceEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SourceEnumTypeHandler<E extends SourceEnum<?>> extends BaseTypeHandler<E> {
    private final SourceEnumGenericConverter sourceEnumGenericConverter;
    private final Class<E> enumClass;
    public SourceEnumTypeHandler(Class<E> type, SourceEnumGenericConverter sourceEnumGenericConverter) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }else if(!sourceEnumGenericConverter.isSourceEnum(type)){
            throw new IllegalArgumentException(type.getName() + " is not a legal SourceEnum, require source is Integer or String");
        }
        this.sourceEnumGenericConverter = sourceEnumGenericConverter;
        this.enumClass = type;
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            Object source = parameter.source();
            if(source instanceof Integer){
                ps.setInt(i, (Integer) source);
            }else{
                ps.setString(i, (String) source);
            }
        } else {
            ps.setObject(i, parameter.source(), jdbcType.TYPE_CODE);
        }

    }
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return sourceEnumGenericConverter.deserialize(rs.getObject(columnName), this.enumClass);
    }
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return sourceEnumGenericConverter.deserialize(rs.getObject(columnIndex), this.enumClass);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return sourceEnumGenericConverter.deserialize(cs.getObject(columnIndex), this.enumClass);
    }
}
